using Glpt.Common;
using Glpt.CommSearch;
using Glpt.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace Glpt.Task
{
    /// <summary>
    /// 导出文件任务
    /// </summary>
    public class ExportFileTask
    {
        private BackgroundWorker bwt = null;
        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public ExportFileTask()
        {
        }
        /// <summary>
        /// 测试接口
        /// </summary>
        /// <param name="function_id">功能号</param>
        /// <param name="tradedate">业务日期</param>
        public List<string> SetParams(string function_id, string tradedate)
        {
            return SetParams(0, function_id, "", tradedate);
        }
        /// <summary>
        /// 参数设置
        /// </summary>
        /// <param name="db_no">数据库编号</param>
        /// <param name="function_id">功能编号</param>
        /// <param name="task_id">任务编号</param>
        /// <param name="tradedate">业务日期</param>
        public List<string> SetParams(int db_no, string function_id, string task_id, string tradedate)
        {
            BaseInterFace bif = new BaseInterFace(db_no);
            string sql = "SELECT * FROM TB_EXPORT_LIST WHERE TASK_FUNCTION_ID=" + function_id + " AND ENABLE_FLAG='1' ORDER BY EXPORT_ID";
            DataTable dt_list = bif.ExecSelect(sql);
            DataRow[] drs = dt_list.Select("EXPORT_ID=-1");//动态取
            if (drs.Length > 0)
                dt_list = CommFuns.GetDynamicProc(dt_list, drs[0]["PARAMS_NAME"].ToString(), function_id, tradedate);
            List<string> files = new List<string>();
            foreach (DataRow dr in dt_list.Rows)
            {
                if (bwt != null && bwt.CancellationPending)
                    throw new Exception("线程被取消");
                string func_id = dr["FUNCTION_ID"].ToString();
                string filename = Funcs.ReplaceWord(dr["TARGET_FILE"].ToString(), tradedate).Trim();
                string encode_name = dr["ENCODE"].ToString().Trim();
                CommSearchInfo csinfo = new CommSearchInfo(func_id, false);
                string[] inputName = dr["PARAMS_NAME"].ToString().Split(new char[] { ';' });
                string[] inputValue = dr["PARAMS_VALUE"].ToString().Split(new char[] { ';' });
                foreach (InputCondition ic in csinfo.Input)
                {
                    for (int k = 0; k < inputName.Length; k++)
                    {
                        if (ic.VAR_NAME.Equals(inputName[k]))
                        {
                            ic.CurServerTime = Funcs.StrToDataTime(tradedate);
                            ic.DEFAULT_VALUE = inputValue[k];
                            filename = filename.Replace("[" + ic.VAR_NAME + "]", ic.InputValue.ToString());
                            break;
                        }
                    }
                }
                csinfo.InputValue = csinfo.GetAllInputValue(false);
                csinfo.ResultTable = csinfo.SearchResult(bwt, csinfo.InputName, csinfo.InputValue, -1);
                System.IO.FileInfo sfile = new System.IO.FileInfo(filename);
                if (sfile.Exists) sfile.Delete();
                if (!sfile.Directory.Exists) sfile.Directory.Create();
                if (encode_name.Length > 0)
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false, CommFuns.GetEncoding(encode_name)))
                    {
                        for (int i = 0; i < csinfo.ResultTable.Rows.Count; i++)
                        {
                            sw.WriteLine(csinfo.ResultTable.Rows[i][0].ToString());
                        }
                        sw.Flush();
                        sw.Close();
                    }
                }
                else if (filename.ToLower().EndsWith(".xml"))
                    csinfo.ExportToXML(filename);
                else if (filename.ToLower().EndsWith(".dbf"))
                    csinfo.ExportToDBF(filename);
                else
                    csinfo.ExportToExcel(filename, false, true, false, false, null);
                files.Add(filename);
            }
            return files;
        }

        /// <summary>
        /// 后台任务对象
        /// </summary>
        public BackgroundWorker BackgroundWorkerTask
        {
            get
            {
                return bwt;
            }
            set
            {
                bwt = value;
            }
        }

        /// <summary>
        /// 释放内存
        /// </summary>
        public void Dispose()
        {
            try
            {
                GC.Collect();
            }
            catch { }
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        ~ExportFileTask()
        {
            Dispose();
        }
    }
}
